﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc; 
using Tools.Framework;
using System.IO;
using System.Net.Mail;
using System.Text;
using System.Net;
using System.Reflection;

namespace Base.Framework
{
    [UAuthFilter]
    public class BaseController : UtilController
    {

        #region 文件上传
        /// <summary>
        /// 统一异步文件上传
        /// </summary>
        /// <returns></returns>
      
        public virtual ActionResult UploadFile()
        {
            try
            {
                var fileuploadResult = UploadAllMessageResultFile(RequestContext.HttpContext.Request.Files);
                return Json(fileuploadResult);
            }
            catch (Exception e)
            {
                return Json(e);
            }
        }


        /// <summary>
        /// 统一上传文件
        /// </summary>
        /// <returns></returns>
        public MessageResult UploadAllMessageResultFile(HttpFileCollectionBase files)
        {
            var fileList = new List<Tuple<string, int>>();

            var urlhost = RequestContext.HttpContext.Request.Url.Host;

            string filename; //源文件名
            string fileType; //源文件文件后缀
            string newfilename; //新文件名称
            string filesavepath;//新文件保存位置
            string vitualPath = System.Web.Configuration.WebConfigurationManager.AppSettings["fileUploadVitualPath"];

            if (files.Count < 1)
            {
                return new MessageResult() {success = false,code = "error",msg = "无上传文件域" };
            }

            for (int i = 0; i < files.Count; i++)
            {
                var file = files[i];
                if (file.ContentLength > 0)
                {
                    filename = file.FileName;
                    fileType = filename.Substring(filename.LastIndexOf("."), filename.Length - filename.LastIndexOf("."));//获取后缀的
                    newfilename = Guid.NewGuid() + fileType;
                    if(!System.IO.Directory.Exists(Server.MapPath(vitualPath)))
                        System.IO.Directory.CreateDirectory(Server.MapPath(vitualPath));
                    filesavepath = Server.MapPath(vitualPath + newfilename);
                    file.SaveAs(filesavepath);
                    fileList.Add(new Tuple<string, int>(vitualPath + newfilename,file.ContentLength));
                }

            }
            LogHelper.Write(message: "文件上传记录：" + fileList.Count + ",来源：" + RequestContext.HttpContext.Request.Url.AbsoluteUri + ":文件信息：【" + fileList.ToJsonString() + "】");
            return new MessageResult() { msg = "上传成功！文件数量：" + fileList.Count, data = fileList.Select(a => a.Item1).ToList()};
        } 
        #endregion

        #region --发送邮件--
        ///<summary>
        /// 发送邮件
        ///</summary>
        ///<param name="sendEmailAddress">发件人邮箱</param>
        ///<param name="sendEmailPwd">发件人密码</param>
        ///<param name="msgToEmail">收件人邮箱地址</param>
        ///<param name="title">邮件标题</param>
        ///<param name="content">邮件内容</param> 
        /// <param name="host"></param>
        /// <returns></returns>
        public static int SendEmail(string sendEmailAddress, string sendEmailPwd, string msgToEmail, string title, string content, string host)
        {

            try
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(sendEmailAddress);
                //可以利用MailMessage.To.Add方法增加要发送的邮件地址
                //  message.To.Add(new MailAddress("296169666@qq.com"));
                message.To.Add(new MailAddress(msgToEmail));
                message.Subject = title;
                message.Body = content;
                //邮件主题
                message.Subject = title;
                //主题编码
                message.SubjectEncoding = Encoding.UTF8;
                //邮件正文
                message.Body = content;
                //正文编码
                message.BodyEncoding = Encoding.UTF8;
                //设置为HTML格式
                message.IsBodyHtml = true;
                //优先级
                message.Priority = MailPriority.High;
                //添加附件
                // Attachment a = new Attachment(@"C:/Users/Administrator/Desktop/smtpclient.rar");
                //message.Attachments.Add(a);
                //设置邮箱的地址或IP
                SmtpClient client = new SmtpClient(host);
                //设置邮箱端口，pop3端口:110, smtp端口是:25
                client.Port = 25;
                //设置超时时间
                client.Timeout = 9999;
                //要输入邮箱用户名与密码
                client.Credentials = new NetworkCredential(sendEmailAddress, sendEmailPwd);
                client.Send(message);
                return 1;

            }
            catch (Exception ex)
            {
                return 0;
            }

        }

        #endregion
    }
}
